<template>
  <div id="upload">
    <div class="row">
      <div class="col-md-12">
        <blockquote class="panel-primary small bg-info">
          <input type="text" v-model="baseUrl">
          <span v-text="uploadUrl"></span>
          <span>&nbsp;支持上传的文件格式:[jpg,gif,png,jpeg]</span>
        </blockquote>
      </div>
      <div class="col-md-12">
        <table class="table table-striped table-bordered table-hover">
          <tbody>
            <tr>
              <td width="60%" rowspan="3"><img class="show-img" :src="resUrl"></td>
              <td><input type='file' v-on:change="uploadOne($event)"></td>
            </tr>
            <tr>
              <td><input @click="clear" class="btn btn-primary btn-block" type="button" value="清除" ></td>
            </tr>
            <tr>
              <td>
                <pre v-if="resUrl" v-text="res"></pre>
                <pre v-else>{}</pre>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>
<script>
  import {baseUrl, uploadUrl} from '../assets/js/setting.js'
  import bus from '../assets/js/bus.js'
  import mixin from '../assets/js/mixin.js'
  export default{
    created () {
      bus.$on('changeBaseUrl', this.changeBaseUrl)
    },
    data: () => {
      return {
        res: {res: {arr: [{url: ''}]}},
        baseUrl: baseUrl,
        uploadUrl: uploadUrl
      }
    },
    computed: {
      resUrl () {
        if (this.res.res.arr[0].url) {
          return this.baseUrl + this.res.res.arr[0].url
        } else {
          return ''
        }
      }
    },
    mixins: [mixin],
    methods: {
      // 清除上传后的结果
      clear () {
        this.res = {res: {arr: [{url: ''}]}}
      },
      // 上传一个文件
      uploadOne (ev) {
        var files = ev.path[0].files[0]
        var formData = new FormData()
        formData.append('files', files)
        formData.append('file_type', 'image')
        let loading = this.$loading({fullscreen: true, text: '正在上传数据...'})
        this.$http.post(this.baseUrl + this.uploadUrl, formData, {
          processData: false,
          contentType: false
        })
        .then((res) => {
          loading.close()
          if (res.status === 200) {
            this.res = res.data
          } else {
            alert(JSON.stringify(res))
          }
        })
        .catch((err) => {
          loading.close()
          console.log('err:', err)
        })
      }
    }
  }
</script>
<style scoped>
  #upload{
    margin-top: 60px;
  }
  .show-img{
    max-width: 630px;
  }
</style>
